﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using TcpServer.User;
using System.Threading;
using System.Windows.Forms;


namespace TcpServer.ThreadManage
{
    class ListenerThread
    {
        public void StartListener()
        {





        }
        /// <summary>
        /// 接收客户端发来的链接
        /// 在10086端口的监听
        /// </summary>
        public static void ListenClientConnect()
        {
            TcpClient NewClient = null;
            while (true)
            {
                try
                {
                    NewClient = Program.MyListener.AcceptTcpClient();
                }
                catch (Exception)
                {
                    //当MyListener.Stop()的时候，引发此
                    break;
                }

                //if (Program.UserList.Count > 0)         //如果客户端链接里面有东西
                //{
                //    for (int i = 0; i < Program.UserList.Count; i++)
                //    {
                //        Program.UserList[i].Close();        //关闭之前的链接
                //    }
                //}
                UserClass UserClient = new UserClass(NewClient,10086);
                UserClient.SendData("欢迎来到我的服务器\r\n");
                Thread ClientReceiveThread = new Thread(new ThreadStart(UserClient.ReciveData));
                UserClient.UserThread = ClientReceiveThread;
                UserClient.UserThread.IsBackground = true;
                UserClient.UserThread.Start();
                Program.UserList.Add(UserClient);
                UserClient.ListIndexID = Program.UserList.IndexOf(UserClient);
                
                
                

            }
        }


        /// <summary>
        /// 接收客户端发来的链接 
        /// 对12345端口的监听
        /// </summary>
        public static void ListenClientConnect2()
        {
            TcpClient NewClient = null;
            while (true)
            {
                try
                {
                    NewClient = Program.MyListener2.AcceptTcpClient();
                }
                catch (Exception)
                {
                    //当MyListener.Stop()的时候，引发此
                    break;
                }

                //if (Program.UserList.Count > 0)         //如果客户端链接里面有东西
                //{
                //    for (int i = 0; i < Program.UserList.Count; i++)
                //    {
                //        Program.UserList[i].Close();        //关闭之前的链接
                //    }
                //}
                UserClass UserClient = new UserClass(NewClient,12345,1);//这里把默认构造函数的NewPort变量赋值为1；
                UserClient.SendData("欢迎来到我的服务器\r\n");
                Thread ClientReceiveThread = new Thread(new ThreadStart(UserClient.ReciveData));
                UserClient.UserThread = ClientReceiveThread;
                UserClient.UserThread.IsBackground = true;
                UserClient.UserThread.Start();
                Program.UserList.Add(UserClient);
                UserClient.ListIndexID = Program.UserList.IndexOf(UserClient);




            }
        }


        /// <summary>
        /// 接收客户端发来的链接 
        /// 对12346端口的监听 进N37
        /// </summary>
        public static void ListenClientConnect3()
        {
            TcpClient NewClient = null;
            while (true)
            {
                try
                {
                    NewClient = Program.MyListener3.AcceptTcpClient();
                }
                catch (Exception)
                {
                    //当MyListener.Stop()的时候，引发此
                    break;
                }

                UserClass UserClient = new UserClass(NewClient,12346, 2);//这里把默认构造函数的NewPort变量赋值为2；
                UserClient.SendData("欢迎来到我的服务器\r\n");
                Thread ClientReceiveThread = new Thread(new ThreadStart(UserClient.ReciveData));
                UserClient.UserThread = ClientReceiveThread;
                UserClient.UserThread.IsBackground = true;
                UserClient.UserThread.Start();
                Program.UserList.Add(UserClient);
                UserClient.ListIndexID = Program.UserList.IndexOf(UserClient);
            }
        }


        /// <summary>
        /// 接收客户端发来的链接 
        /// 对12347端口的监听
        /// </summary>
        public static void ListenClientConnect4()
        {
            TcpClient NewClient = null;
            while (true)
            {
                try
                {
                    NewClient = Program.MyListener4.AcceptTcpClient();
                }
                catch (Exception)
                {
                    //当MyListener.Stop()的时候，引发此
                    break;
                }

                UserClass UserClient = new UserClass(NewClient,12347, 3);//这里把默认构造函数的NewPort变量赋值为3；
                UserClient.SendData("欢迎来到我的服务器\r\n");
                Thread ClientReceiveThread = new Thread(new ThreadStart(UserClient.ReciveData));
                UserClient.UserThread = ClientReceiveThread;
                UserClient.UserThread.IsBackground = true;
                UserClient.UserThread.Start();
                Program.UserList.Add(UserClient);
                UserClient.ListIndexID = Program.UserList.IndexOf(UserClient);
            }
        }


        /// <summary>
        /// 接收客户端发来的链接 
        /// 对12344端口的监听 进N37
        /// </summary>
        public static void ListenClientConnect5()
        {
            TcpClient NewClient = null;
            while (true)
            {
                try
                {
                    NewClient = Program.MyListener5.AcceptTcpClient();
                }
                catch (Exception)
                {
                    //当MyListener.Stop()的时候，引发此
                    break;
                }

                UserClass UserClient = new UserClass(NewClient, 12344, 2);//这里把默认构造函数的NewPort变量赋值为2；
                UserClient.SendData("欢迎来到我的服务器，进N37\r\n");
                Thread ClientReceiveThread = new Thread(new ThreadStart(UserClient.ReciveData));
                UserClient.UserThread = ClientReceiveThread;
                UserClient.UserThread.IsBackground = true;
                UserClient.UserThread.Start();
                Program.UserList.Add(UserClient);
                UserClient.ListIndexID = Program.UserList.IndexOf(UserClient);
            }
        }

        /// <summary>
        /// 接收客户端发来的链接 
        /// 对12348端口的监听 进N39
        /// </summary>
        public static void ListenClientConnect6()
        {
            TcpClient NewClient = null;
            while (true)
            {
                try
                {
                    NewClient = Program.MyListener6.AcceptTcpClient();
                }
                catch (Exception)
                {
                    //当MyListener.Stop()的时候，引发此
                    break;
                }

                UserClass UserClient = new UserClass(NewClient, 12348, 4);//这里把默认构造函数的NewPort变量赋值为4；进N39
                UserClient.SendData("欢迎来到我的服务器，进N39\r\n");
                Thread ClientReceiveThread = new Thread(new ThreadStart(UserClient.ReciveData));
                UserClient.UserThread = ClientReceiveThread;
                UserClient.UserThread.IsBackground = true;
                UserClient.UserThread.Start();
                Program.UserList.Add(UserClient);
                UserClient.ListIndexID = Program.UserList.IndexOf(UserClient);
            }
        }

        /// <summary>
        /// 接收客户端发来的链接 
        /// 对12349端口的监听 进n40
        /// </summary>
        public static void ListenClientConnect7()
        {
            TcpClient NewClient = null;
            while (true)
            {
                try
                {
                    NewClient = Program.MyListener7.AcceptTcpClient();
                }
                catch (Exception)
                {
                    //当MyListener.Stop()的时候，引发此
                    break;
                }

                UserClass UserClient = new UserClass(NewClient, 12349, 5);//这里把默认构造函数的NewPort变量赋值为5；进n40
                UserClient.SendData("欢迎来到我的服务器,进n40\r\n");
                Thread ClientReceiveThread = new Thread(new ThreadStart(UserClient.ReciveData));
                UserClient.UserThread = ClientReceiveThread;
                UserClient.UserThread.IsBackground = true;
                UserClient.UserThread.Start();
                Program.UserList.Add(UserClient);
                UserClient.ListIndexID = Program.UserList.IndexOf(UserClient);
            }
        }


        /// <summary>
        /// 接收服务器发来的信息
        /// </summary>
        public static void ListenCMDConnect()
        {
            TcpClient CMDClient = null;
            while (true)
            {
                try
                {
                    CMDClient = Program.CMDListener.AcceptTcpClient();
                }
                catch (Exception)
                {
                    //当MyListener.Stop()的时候，引发此
                    break;
                }
                System.GC.Collect();
                ServerClient SerClient = new ServerClient(CMDClient);
                SerClient.SendData("链接到服务器TCPCMD命令行\r\n");
                Thread SerClientReceiveThread = new Thread(new ThreadStart(SerClient.ReciveData));
                SerClient.SerCliThread = SerClientReceiveThread;
                SerClient.SerCliThread.IsBackground = true;
                SerClient.SerCliThread.Start();
                Program.SerList.Add(SerClient);
                SerClient.ListIndexID = Program.SerList.IndexOf(SerClient);

            }
        }

        public static void CheckConnctTimeOut()
        {
            while (true)
            {
                //先睡眠10分钟
                Thread.Sleep(60000 * 10);
                for (int i = 0; i < Program.UserList.Count; i++)
                {
                    //对于单片机连接，如果大于10分钟没有有效字符的通信了，就做停止线程工作
                    if ((DateTime.Now - Program.UserList[i].LastConnTime).TotalMinutes > 30)
                    {
                        Console.WriteLine("终止超时设备长链接，具体查LOG文件日志" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        Log.Error("ListenerThread", "线程ID=" + Thread.CurrentThread.ManagedThreadId.ToString() + ";终止超时设备长连接，终止的对应设备MeterIP="+Program.UserList[i].MeterIP);
                        Program.UserList[i].Close();
                    }
                }

                for (int i = 0; i < Program.SerList.Count; i++)
                {
                    //对于接收指令的CMD
                    if ((DateTime.Now - Program.SerList[i].LastConnTime).TotalHours > 10)
                    {
                        Console.WriteLine("终止超时设备长链接，具体查LOG文件日志" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        Log.Error("ListenerThread", "线程ID=" + Thread.CurrentThread.ManagedThreadId.ToString() + ";终止超时设备长连接，终止的对应Server链接线程ID=" + Program.SerList[i].SerCliThread.ManagedThreadId.ToString());
                        Program.SerList[i].Close();
                    }
                }
                
            }
        }

        public static void HeartBeat()
        {
            while (true)
            {
                TcpClient HeartBeatClient = new TcpClient();
                try
                {
                    HeartBeatClient.Connect(IPAddress.Parse("115.28.30.250"), 10084);
                    //HeartBeatClient.Connect(IPAddress.Parse("192.168.2.101"), 10084);
                    Thread.Sleep(1000);
                    NetworkStream NStream = HeartBeatClient.GetStream();
                    string str = "MyHeartBeat";
                    byte[] WriteBuffer = Encoding.UTF8.GetBytes(str);
                    if (NStream.CanWrite)
                    {
                        NStream.Write(WriteBuffer, 0, WriteBuffer.Length);
                        Console.WriteLine("发送心跳完成");
                    }
                    else
                    {
                        Console.WriteLine("Sorry.  You cannot write to this NetworkStream.");
                        Log.Error("SendDataError", "发送心跳出错,stream不可读引起");
                    }
                    NStream.Close();
                    NStream.Dispose();
                    HeartBeatClient.Close();
                    
                }
                catch (Exception e)
                {

                    MessageBox.Show(e.Message+",连接本机10084端口失败,请确保看门狗程序开启");
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }
                
                //睡眠10秒
                Thread.Sleep(1000 * 10);

            }
        }




    }
}
